<template>
  <!-- 新病历改版 -->
  <section>
    <br />
    <div style="text-align:right;">
      <el-button @click="dialogSelectTemplate = true">选择模板</el-button>
      <el-button v-if="patientInfo.name" @click="dialogHistoryCase = true"
        >复制病历</el-button
      >
    </div>
    <br />
    <br />
    <blForm
      ref="blForm"
      :dataForm="dataForm"
      :doctorId="doctorId"
      :deptId="deptId"
      :cureFirstVisitRecord="cureFirstVisitRecord"
      @submit="blFormSubmit"
      @change="onChangeForm"
    ></blForm>
    <el-form
      ref="form"
      :model="form"
      @submit.native.prevent="onSubmit"
      label-width="140px"
    >
      <el-form-item label="过敏史：">
        <el-radio-group v-model="existAllergy" @change="onExistAllergyChange">
          <el-radio :label="true">有</el-radio>
          <el-radio :label="false">无</el-radio>
        </el-radio-group>
        <div v-if="existAllergy">
          <guoMinShi
            v-model="form.curePatientAllergy"
            :isAdd="true"
            @onAdd="onAddGuoMin"
          ></guoMinShi>
        </div>
      </el-form-item>
      <el-form-item label>
        <el-button
          :type="btnShow.jws ? 'primary' : 'default'"
          style="margin:0 10px 5px 0;"
          @click="btnShow.jws = true"
          >+既往史</el-button
        >
        <el-button
          :type="btnShow.grs ? 'primary' : 'default'"
          style="margin:0 10px 5px 0;"
          @click="btnShow.grs = true"
          >+个人史</el-button
        >
        <el-button
          :type="btnShow.jzs ? 'primary' : 'default'"
          style="margin:0 10px 5px 0;"
          @click="btnShow.jzs = true"
          >+家族史</el-button
        >
        <el-button
          v-if="patientInfo.sex == 2 && patientInfo.age < 18"
          :type="btnShow.jdtcs ? 'primary' : 'default'"
          style="margin:0 10px 5px 0;"
          @click="btnShow.jdtcs = true"
          >+经带胎产史</el-button
        >
        <el-button
          :type="btnShow.yyjzs ? 'primary' : 'default'"
          style="margin:0 10px 5px 0;"
          @click="btnShow.yyjzs = true"
          >+疫苗接种史</el-button
        >
        <el-button
          :type="btnShow.sys ? 'primary' : 'default'"
          style="margin:0 10px 5px 0;"
          @click="btnShow.sys = true"
          >+实验室及辅助检查</el-button
        >
      </el-form-item>
      <el-form-item
        v-show="btnShow.jws"
        label="既往史："
        prop="curePatientHistory.pastHistory"
      >
        <el-input
          v-model="form.curePatientHistory.pastHistory"
          type="textarea"
          :rows="2"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-show="btnShow.grs"
        label="个人史："
        prop="curePatientHistory.personalHistory"
      >
        <el-input
          v-model="form.curePatientHistory.personalHistory"
          type="textarea"
          :rows="2"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-show="btnShow.jzs"
        label="家族史："
        prop="curePatientHistory.familyHistory"
      >
        <el-input
          v-model="form.curePatientHistory.familyHistory"
          type="textarea"
          :rows="2"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="patientInfo.sex == 2 && patientInfo.age < 18"
        v-show="btnShow.jdtcs"
        label="经带胎产史："
        prop="curePatientHistory.afterTheBirth"
      >
        <el-input
          v-model="form.curePatientHistory.afterTheBirth"
          type="textarea"
          :rows="2"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-show="btnShow.yyjzs"
        label="疫苗接种史："
        prop="curePatientHistory.seedlingsHistory"
      >
        <el-input
          v-model="form.curePatientHistory.seedlingsHistory"
          type="textarea"
          :rows="2"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-show="btnShow.sys"
        label="实验室及辅助检查："
        prop="curePatientHistory.checkupHistory"
      >
        <el-input
          v-model="form.curePatientHistory.checkupHistory"
          type="textarea"
          :rows="2"
        ></el-input>
      </el-form-item>
      <el-form-item label>
        <div class="form-tool">
          <div>
            <el-button
              type="primary"
              :loading="btnLoading"
              style="width:100px;"
              native-type="submit"
              >保存</el-button
            >
          </div>
          <div>
            <!-- <el-button @click="dialogSaveTemplate=true">
              <i class="iconfont iconcunchu vertical-middle"></i>
              <span class="vertical-middle">存为模板</span>
            </el-button> -->
            <el-button v-if="templateSave.t0 == false" @click="onPrint">
              <i
                class="iconfont icondayin vertical-middle"
                style="font-size:20px;"
              ></i>
              <span class="vertical-middle">打印病历</span>
            </el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <dialogSaveTemplate
      v-model="dialogSaveTemplate"
      :cureFirstVisitRecord="cureFirstVisitRecord"
      :dataForm="dataForm"
      :doctorId="doctorId"
      :deptId="deptId"
    ></dialogSaveTemplate>
    <selectTemplate
      v-model="dialogSelectTemplate"
      @success="onSelectTemplate"
      :deptId="deptId"
      :doctorId="doctorId"
    ></selectTemplate>
    <dialogHistoryCase
      v-model="dialogHistoryCase"
      :patientInfo="patientInfo"
      :copy="true"
      @copyBL="onCopyBL"
    ></dialogHistoryCase>
    <iframe
      ref="iframe1"
      frameborder="0"
      height="0px"
      width="0px"
      src="/print/caseReport.html"
    ></iframe>
  </section>
</template>
<script>
export default {
  components: {
    blForm: () => import("./_com/blForm.vue"),
    guoMinShi: () => import("@/pages/_com/guoMinShi.vue"),
    dialogSaveTemplate: () => import("../_jz/_com/dialogSaveTemplate.vue"),
    selectTemplate: () => import("./_com/selectTemplate.vue"),
    dialogHistoryCase: () => import("../_com/dialogHistoryCase.vue"),
  },
  computed: {
    templateSave() {
      return this.$store.state.doctorMZ.templateSave;
    },
    patientInfo() {
      return this.$store.state.doctorMZ.patientInfo;
    },
    //职业
    occupationEnum() {
      return this.$store.state.doctorMZ.enum.occupationEnum;
    },
    //民族
    nationEnum() {
      return this.$store.state.doctorMZ.enum.nationEnum;
    },
    patientId() {
      return this.$store.state.doctorMZ.patientId;
    },
    doctorId() {
      return this.$store.state.doctorMZ.doctorId;
    },
    deptId() {
      return this.$store.state.doctorMZ.deptId;
    },
    cureId() {
      return this.$store.state.doctorMZ.cureId;
    },
  },
  data() {
    return {
      isOpenEdit: false, //验证是否改动
      btnLoading: false,
      isNewUser: true, //是否第一次就诊
      dialogSaveTemplate: false,
      cureFirstVisitRecord: [], //初步诊断
      dialogSelectTemplate: false,
      dialogHistoryCase: false, //历史病历
      dataForm: [],
      existAllergy: false, //过敏史
      btnShow: {
        jws: false,
        grs: false,
        jzs: false,
        jdtcs: false,
        yyjzs: false,
        sys: false,
      },
      form: {
        cureDynamic: {
          cureId: "",
          hpId: "",
          patientId: "",
          deptId: "",
          doctorId: "",
          dynamicType: 1,
          dynamicTemplateId: "",
          dynamicMedical: "",
          id: "",
          medicalCreateTime: "",
        },
        curePatientAllergy: [],
        curePatientHistory: {
          pastHistory: "",
          personalHistory: "",
          familyHistory: "",
          seedlingsHistory: "",
          afterTheBirth: "",
          checkupHistory: "",
          id: "",
        },
      },
    };
  },
  created() {
    let th = this;
    th.isNewUser = th.$route.query.isNew;
    th.form.cureDynamic.hpId = th.adminUser.hpId;
    th.form.cureDynamic.patientId = th.patientId;
    th.form.cureDynamic.cureId = th.cureId;
    th.form.cureDynamic.deptId = th.jieMi(th.$route.query.deptId);
    th.form.cureDynamic.doctorId = th.jieMi(th.$route.query.doctorId);
  },
  mounted() {
    let th = this;
    th.getData();
  },
  methods: {
    //表单变化事件
    onChangeForm() {
      const th = this;
      //开启修改状态
      th.$store.commit("Set_templateSave", {
        key: "t0",
        value: true,
      });
    },
    //打印
    onPrint() {
      let th = this;
      let json = {
        hospital: {
          name: th.adminUser.hospitalName,
          logo: th.adminUser.printLogo,
          province: th.adminUser.hospitalProvince,
          city: th.adminUser.hospitalCity,
          district: th.adminUser.hospitalDistrict,
          address: th.adminUser.hospitalAddress,
        },
        professionalDeptName: th.$route.query.professionalDeptName,
        time: th.form.cureDynamic.medicalCreateTime,
        doctorName: th.$route.query.doctorName,
        cureFirstVisitRecord: th.cureFirstVisitRecord, //诊断
        patientInfo: th.patientInfo,
        dataForm: th.dataForm, //动态病历
        curePatientAllergy: th.form.curePatientAllergy, //过敏史
        curePatientHistory: th.form.curePatientHistory, //个人历史
        occupationEnum: th.occupationEnum, //职业
        nationEnum: th.nationEnum, //婚姻
        traditionRecipe: [], //中药
        westwardRecipe: [], //西药
      };
      th.$refs["iframe1"].contentWindow.postMessage(
        json,
        `${window.location.origin}/print/caseReport.html`
      );
    },
    //病历表单提交
    blFormSubmit(obj) {
      let th = this;
      let allergy=th.form.curePatientAllergy;
      allergy.map((it,index)=>{
        if(it.allergicDegree==='' && it.allergens==='' && it.allergicReaction===''){
            th.form.curePatientAllergy.remove(index,1);
        }
      })
      th.form.cureDynamic.dynamicMedical = obj;
      let j = {
        cureMedicalDTO: JSON.stringify(th.form.cureDynamic),
        curePatientAllergyDTO: null,
        curePatientHistoryDTO: JSON.stringify(th.form.curePatientHistory),
      };
      if (th.existAllergy) {
        j.curePatientAllergyDTO = JSON.stringify(th.form.curePatientAllergy);
      }
      let add = function() {
        th.btnLoading = true;
        th.$api
          .addcureDynamicmedical(j)
          .then((res) => {
            if (res.executed) {
              th.$message.success("保存成功");
              th.form.cureDynamic.id = res.data;
              th.form.cureDynamic.medicalCreateTime = th.$utils.FormatTime(
                "yyyy-MM-dd",
                new Date().getTime()
              );
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
            th.$nextTick(function() {
              th.isOpenEdit = true;
              th.$store.commit("Set_templateSave", {
                key: "t0",
                value: false,
              });
            });
          })
          .catch((res) => {
            th.btnLoading = false;
            th.isOpenEdit = true;
            th.$message.error(res.message);
          });
      };
      let update = function() {
        th.btnLoading = true;
        th.$api
          .updatecureDynamicmedical(j)
          .then((res) => {
            if (res.executed) {
              th.$message.success("保存成功");
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
            th.$nextTick(function() {
              th.isOpenEdit = true;
              th.$store.commit("Set_templateSave", {
                key: "t0",
                value: false,
              });
            });
          })
          .catch((res) => {
            th.btnLoading = false;
            th.isOpenEdit = true;
            th.$message.error(res.message);
          });
      };
      th.$refs["form"].validate((v) => {
        if (v) {
          th.isOpenEdit = false;
          th.dataForm = obj;
          if (th.form.cureDynamic.id) {
            update();
          } else {
            add();
          }
        }
      });
    },
    //复制病历
    onCopyBL(obj) {
      let th = this;
      th.form.curePatientHistory =
        obj.cureMedicalInfoResponse.curePatientHistory || {};
      let curePatientAllergy = obj.cureMedicalInfoResponse.curePatientAllergy;
      th.form.curePatientAllergy = curePatientAllergy || [];
      if (curePatientAllergy && curePatientAllergy.length > 0)
        th.existAllergy = true;
      th.forDataForm(obj.cureMedicalInfoResponse.dynamicFieldBeans || []);
      th.cureFirstVisitRecord =
        obj.cureMedicalInfoResponse.cureFirstVisitRecord || [];
    },
    onSubmit() {
      let th = this;
      th.$refs["blForm"].onSubmit();
    },
    //渲染模板
    forDataForm(obj) {
      this.dataForm = obj;
    },
    //选择模板
    onSelectTemplate(obj) {
      this.forDataForm(obj.templateDynamicFieldBeans);
      this.form.cureDynamic.dynamicTemplateId=obj.id;
      this.cureFirstVisitRecord = [];
    },
    //新增过敏
    onAddGuoMin() {
      let j = {
        cureId: this.cureId,
        patientId: this.patientId,
        allergyId: "",
        allergens: "",
        allergicReaction: "",
        allergicDegree: "",
      };
      this.form.curePatientAllergy.push(j);
    },
    //获取病历
    async getData() {
      let th = this;
      let bl = await th.$api.getcureDynamicdetailid({ cureId: th.cureId });
      if (bl.executed && Object.keys(bl.data).length > 0) {
        th.existAllergy = bl.data.existAllergy;
        if (th.existAllergy) {
          th.form.curePatientAllergy = bl.data.curePatientAllergy;
        }
        th.dataForm = bl.data.cureMedical.templateDynamicFieldBeans;
        th.form.cureDynamic.id = bl.data.cureMedical.id;
        th.form.cureDynamic.dynamicTemplateId = bl.data.cureMedical.templateId;
        th.form.cureDynamic.medicalCreateTime =
          bl.data.cureMedical.medicalCreateTime;
        //判断历史
        if (bl.data.curePatientHistory) {
          th.form.curePatientHistory = bl.data.curePatientHistory;
          //判断按钮
          if (bl.data.curePatientHistory.familyHistory) th.btnShow.jzs = true;
          if (bl.data.curePatientHistory.pastHistory) th.btnShow.jws = true;
          if (bl.data.curePatientHistory.personalHistory) th.btnShow.grs = true;
          if (bl.data.curePatientHistory.seedlingsHistory)
            th.btnShow.yyjzs = true;
          if (bl.data.curePatientHistory.afterTheBirth) th.btnShow.jdtcs = true;
          if (bl.data.curePatientHistory.checkupHistory) th.btnShow.sys = true;
        }
        th.cureFirstVisitRecord = bl.data.cureFirstVisitRecord; //诊断
      } else {
        //没有查询到
        //判断是否填写病例
        th.isOpenEdit = true;
        let j = {
          templateType: 1,
          deptId: th.deptId,
        };
        let mb = await th.$api.defaulttemplateDynamic(j);
        if (mb.executed) {
          th.dataForm = mb.data.templateDynamicFieldBeans;
          th.form.cureDynamic.dynamicTemplateId = mb.data.id;
        }
      }
      //判断是否新用户
      if (th.isNewUser) {
        //获取过敏
        let j = { patientId: th.patientId };
        let gms = await th.$api.getAllergyById(j);
        if (gms.executed) {
          if (gms.patientAllergyList && gms.patientAllergyList.length > 0) {
            th.existAllergy = true;
            th.form.curePatientAllergy = gms.patientAllergyList;
          }
        }
        //个人史
        let res2 = await th.$api.getPatientHistoryById(j);
        let patientHistory = res2.patientHistory;
        if (res2.executed && patientHistory) {
          th.btnShow.jws = patientHistory.pastHistory ? true : false;
          th.form.curePatientHistory.pastHistory = patientHistory.pastHistory;
          th.btnShow.grs = patientHistory.personalHistory ? true : false;
          th.form.curePatientHistory.personalHistory =
            patientHistory.personalHistory;
          th.btnShow.jzs = patientHistory.familyHistory ? true : false;
          th.form.curePatientHistory.familyHistory =
            patientHistory.familyHistory;
          th.btnShow.yyjzs = patientHistory.seedlingsHistory ? true : false;
          th.form.curePatientHistory.seedlingsHistory =
            patientHistory.seedlingsHistory;
          th.form.curePatientHistory.afterTheBirth =
            patientHistory.afterTheBirth;
        }
      }
      th.$nextTick(function() {
        th.isOpenEdit = true;
      });
    },
    //过敏史转换
    onExistAllergyChange() {
      const th = this;
      th.form.curePatientAllergy = [];
    },
  },
  watch: {
    dataForm: {
      deep: true,
      handler: function(n) {
        let th = this;
        if (!th.isOpenEdit) return;
        //开启修改状态
        th.$store.commit("Set_templateSave", {
          key: "t0",
          value: true,
        });
      },
    },
    "form.curePatientAllergy": {
      deep: true,
      handler: function() {
        let th = this;
        if (!th.isOpenEdit) return;
        //开启修改状态
        th.$store.commit("Set_templateSave", {
          key: "t0",
          value: true,
        });
      },
    },
    "form.curePatientHistory": {
      deep: true,
      handler: function() {
        let th = this;
        if (!th.isOpenEdit) return;
        //开启修改状态
        th.$store.commit("Set_templateSave", {
          key: "t0",
          value: true,
        });
      },
    },
  },
};
</script>
